<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 依次从个位开始比较，把值依次放到二维数组里面，然后每比较完一位，就从二维数组里面将值取出来
      function radixSort(arr) {
        // mod 和 dev用于每次取出个位，十位百位上的数
        let counter = [],
          mod = 10,
          dev = 1;
        // 找出当前的数组中的最大值
        let max = Math.max(...arr);
        // 并且确定最大比较位数
        let maxDigit = 0;
        while (max != 0) {
          max = parseInt(max / 10);
          maxDigit++;
        }
        for (let i = 0; i < maxDigit; i++, dev *= 10, mod *= 10) {
          for (let j = 0; j < arr.length; j++) {
            let bucket = parseInt((arr[j] % mod) / dev);
            if (counter[bucket] == null) {
              counter[bucket] = [];
            }
            counter[bucket].push(arr[j]);
          }
          let pos = 0;
          for (let j = 0; j < counter.length; j++) {
            let value = null;
            if (counter[j] != null) {
              while ((value = counter[j].shift()) != null) {
                arr[pos++] = value;
              }
            }
          }
        }
        return arr;
      }
      console.log(radixSort([1, 3, 4, 6, 2, 7, 8]));
    </script>
  </body>
</html>
